<?php

namespace app\admin\logic;

use support\Exception\ApiException;
use support\Service\MenuService;
use support\Service\UserRoleService;
use support\Service\UserService;

class UserLogic extends BaseLogic
{

    public function __construct()
    {
        self::$service = new UserService();
    }

    /**
     * 获取用户列表
     * @return array
     */
    public static function getList()
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (isset($param['username']) && $param['username']) {
            $where[] = ["username", 'like', "%{$param['username']}%"];
        }
        $list = UserService::getListPage($where);
        if ($list['total'] <= 0) return message($list);
        foreach ($list['list'] as $k => $v) {
            $list['list'][$k]['roles'] = UserRoleService::getUserRoleList($v['id']);
        }
        return message($list);
    }

    public static function info()
    {
        $info = parent::info(); // TODO: Change the autogenerated stub
        if (!$info['data']) return $info;
        $info['data']['roles'] =UserRoleService::getUserRoleList($info['data']['id']);;
        return $info;
    }

    /**
     * 获取后台用户信息
     * @param $userId
     * @return array
     */
    public static function getUserInfo($userId)
    {
        //获取用户信息
        $user_info = UserService::getUserInfo($userId);
        // 权限节点列表
        if (!isset($user_info['permissionList'])) {
            $permissionList = MenuService::getPermissionsList($userId);
            $user_info['permissionList'] = $permissionList;
        }
        return message($user_info);
    }

    public static function edit()
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (!isset($data['realname']) || empty($data['realname'])) {
            throw new ApiException('请输入用户姓名');
        }
        if (!isset($data['nickname']) || empty($data['nickname'])) {
            throw new ApiException('请输入用户昵称');
        }
        if (!isset($data['email']) || empty($data['email'])) {
            throw new ApiException('请输入用户邮箱');
        }
        if (!isset($data['mobile']) || empty($data['mobile'])) {
            throw new ApiException('请输入手机号');
        }
        if (!isset($data['username']) || empty($data['username'])) {
            throw new ApiException('请输入登录账号');
        }
        if (!isset($data['role_ids']) || empty($data['role_ids'])) {
            throw new ApiException('请选择用户角色');
        }
        if (!$id && (!isset($data['password']) || empty($data['password']))) {
            throw new ApiException('请输入登录密码');
        }
        $save['username'] = trim($data['username']);
        $save['password'] = trim($data['password']);
        $save['email'] = $data['email'];
        $save['realname'] = $data['realname'];
        $save['nickname'] = $data['nickname'];
         //$save['role_ids']=$data['role_ids'];
        $save['mobile'] = $data['mobile'];
        $save['status'] = $data['status'];
        $save['avatar'] = $data['avatar'];
        unset($data['id']);
        if (!$id) {
            $save['password'] = get_password($save['password'] . $save['username']);
            // 用户名重复性验证
            $count = UserService::getUserCountByWhere([["username", '=', $save['username']], ["mark", "=", 1]]);
            if ($count > 0) {
                throw new ApiException('系统中已存在相同的用户名');
            }
            $mobile_count = UserService::getUserCountByWhere([["mobile", '=', $save['mobile']], ["mark", "=", 1]]);
            if ($mobile_count > 0) {
                throw new ApiException('系统中已存在相同的手机号');
            }
        } else {
            if (!$save['password']) {
                unset($save['password']);
            } else {
                $save['password'] = get_password($save['password'] . $save['username']);
            }
            // 用户名重复性验证
            $count = UserService::getUserCountByWhere([["username", '=', $save['username']], ["id", "<>", $id], ["mark", "=", 1]]);
            if ($count > 0) {
                throw new ApiException('系统中已存在相同的用户名');
            }
            $mobile_count = UserService::getUserCountByWhere([["mobile", '=', $save['mobile']], ["id", "<>", $id], ["mark", "=", 1]]);
            if ($mobile_count > 0) {
                throw new ApiException('系统中已存在相同的手机号');
            }
        }
        if ($id == 0) {
            $result = UserService::add($save);
        } else {
            UserService::save($save, $id);
            $result = $id;
        }
        // 删除已存在的用户角色关系数据
        UserRoleService::deleteUserRole($result);
        UserRoleService::insertUserRole($result, $data['role_ids'] ?? []);
        return message();

    }


    /**
     * 修改密码
     * @param $userId 用户ID
     * @return mixed
     */
    public static function updatePwd($userId)
    {
        // 获取参数
        $param = request()->all();
        // 原始密码
        $oldPassword = trim($param['oldPassword']);
        if (!$oldPassword) {
            throw new ApiException('旧密码不能为空');
        }
        // 新密码
        $newPassword = trim($param['newPassword']);
        if (!$newPassword) {
            throw new ApiException('新密码不能为空');
        }
        $userInfo = UserService::getInfo(['id' => $userId]);
        if (!$userInfo) {
            throw new ApiException('用户信息不存在');
        }
        if ($userInfo['password'] != get_password($oldPassword . $userInfo['username'])) {
            throw new ApiException('旧密码输入不正确');
        }
        $item = [
            'password' => get_password($newPassword . $userInfo['username']),
        ];
        $result = UserService::save($item, $userId);
        if (!$result) {
            throw new ApiException('修改失败');
        }
        return message();
    }


    /**
     * 更改用户信息
     * @return void
     */
    public static function updateUserInfo($user_id)
    {
        $data = request()->post();
        $save['address'] = trim($data['address'] ?? '');
        $save['intro'] = trim($data['intro'] ?? '');
        $save['avatar'] = $data['avatar'] ?? '';
        $save['email'] = $data['email'] ?? '';
        $save['gender'] = $data['gender'] ?? 3;
        $save['mobile'] = $data['mobile'] ?? '';
        $save['nickname'] = $data['nickname'] ?? '';
        $save['realname'] = $data['realname'] ?? '';
        UserService::save($save, $user_id);
        return message();
    }


}
